import { createRouter, createWebHashHistory } from 'vue-router';
// ts 类型定义
import type { RouteRecordRaw, Router } from 'vue-router';

// 导入页面组件
import LoginView from '@/views/login/index.vue';
import LayoutView from '@/views/common/layout.vue';
import {useAppStore} from "@/store";
import {PermissionEnum} from "@/config/permission.config";
import PageLayoutView from "@/views/common/page-layout.vue";

import NotFoundView from "@/views/error/not-found.vue";
import NotAllowedView from "@/views/error/not-allowed.vue";

import { usePermissionStore } from "@/store/permission";


declare module "vue-router" {
  interface RouteMeta extends Record<string | number | symbol, unknown> {
    permission?: string
    icon?: string
    title?: string
  }
}

export const MENU_ROUTE_NAME = "menuRoot";

// Router.addRoute 类型
export const routes: Array<RouteRecordRaw> = [
  //{path: '/', name: 'dashboard', component: DashboardView}, /*该页面没有权限无法进入，所以采用动态加载 ，去掉上面import静态加载 */
  //{path: '/', name: 'dashboard', component: () => import('@/views/dashboard/index.vue'), meta: {title: '控制台'}},
  {
    path: "/",
    name: MENU_ROUTE_NAME,
    component: LayoutView,
    redirect: "dashboard",
    children: [
      {
        name: "dashboard",
        path: "dashboard",
        component: () => import("@/views/dashboard/index.vue"),
        meta: {
          permission: PermissionEnum.DASHBOARD,
          title: "控制台",
          icon: "dashboard",
        },
      },
      {
        name: "user",
        path: "user",
        component: PageLayoutView,
        meta: {
          title: "用户",
          icon: "usergroup",
          permission: PermissionEnum.USER,
        },
        redirect: { name: "user-list" },
        children: [
          {
            name: "user-list",
            path: "list",
            component: () => import("@/views/user/index.vue"),
            meta: {
              title: "用户管理",
              icon: "user",
              permission: PermissionEnum.USER_LIST,
            },
          },
          {
            name: "role-list",
            path: "roles",
            component: () => import("@/views/user/roles.vue"),
            meta: {
              title: "角色管理",
              permission: PermissionEnum.USER_ROLES,
              icon: "secured",
            },
          },
        ],
      },
    ],
  },
  { path: "/login", name: "login", component: LoginView },
  //403和404页面
  { path: "/403", name: "not-allowed", component: NotAllowedView },
  { path: "/:pathMatch(.*)*", name: "not-found", component: NotFoundView },
];

const router: Router = createRouter({
  //history: createWebHistory(import.meta.env.BASE_URL), // 地址栏不带# ，import.meta.env.BASE_URL 基础目录
  history: createWebHashHistory(import.meta.env.BASE_URL),// 地址栏带#
  strict: true, //严格模式
  routes,
  scrollBehavior: () => ({left:0 , top:0}) // 页面每次打开都是定位到头部
});

const whiteList: Array<RouteRecordName | undefined | null> = [
  "login",
  "not-found",
  "not-allowed",
];


// 路由守卫
/*router.beforeEach((to, from, next) => {
  // 获取 store的token
  const appStore = useAppStore();
  //console.log("to.meta.title = "+to.meta.title)
  //console.log(appStore.token);
  if (!appStore.token){ // 如果没有token
    whiteList.indexOf(to.path) !== -1 ? next() : next(`/login?redirect=${to.path}`); //是登陆页面的请求就到登陆页面，否则强制跳转到登录页，需要添加/login
  }else if (appStore.token && to.path === "/login") {
    next({ name: "dashboard" });
  }
  next();
});*/
router.beforeEach(async (to, from) => {
  const appStore = useAppStore();

  // todo 动态路由（可以参考无感刷新思路）
  /*const userPermissions = getUserPermissions(); // 从状态管理或其他来源获取用户权限

  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查权限
    const hasPermission = record.meta.permissions.every(permission =>
        userPermissions.includes(permission)
    );

    if (!hasPermission) {
      return next({ name: 'Home' }); // 无权限则重定向
    }
  }*/

  if (!appStore.token) {
    // 将用户重定向到登录页面
    console.log("没有登陆权限")
    return whiteList.indexOf(to.name) !== -1 ? true : {path: '/login', query: { redirect: to.fullPath },};
  } else if (appStore.token && to.path === "/login")  {
    console.log("有权限并且为登陆页面")
    //return { name: 'dashboard' }
    return "/";
  }

  // 判断token是否存在，判断当前访问的域名是否合法；
  // 如果不合法，跳转至403页面
  if (to.name && to.name !== "not-found" && to.name !== "not-allowed") {
    console.log("to.name",to.name)
    const permissionStore = usePermissionStore();
    const hasNoPermission = !permissionStore.permissionRouteNamesList.includes(to.name);
    if (appStore.token && hasNoPermission && whiteList.indexOf(to.name) !== -1) {
      console.log("符合跳转到403")
      return {name: "not-allowed"} ;
      //return "/403";
    }
  }

  console.log("from有权限的其他请求",from.path, from.fullPath, from.query.redirect);
  console.log("to有权限的其他请求",to.path, to.fullPath, to.query);
  return true;
});

// 添加用户权限
const addUserPermission = (permission) => {
  // 假设有相应的路由可以添加
  if (permission === 'view_admin') {
    router.addRoute({
      path: '/admin',
      name: 'Admin',
      component: Admin,
      meta: { requiresAuth: true, permissions: ['view_admin'] },
    });
  }
};

// 删除用户权限
const removeUserPermission = (permission) => {
  if (permission === 'view_admin') {
    router.removeRoute('Admin');
  }
};

export default router
